import { Component, ReactNode } from "react";
import { View, Text, Picker, Input } from "@tarojs/components";
import { AtButton, AtList, AtListItem, AtNavBar } from "taro-ui";
import Req from "../../utils/request";
import { isEmpty } from "../../utils/kit";
import "./index.scss";
import Taro from "@tarojs/taro";
import { getInfo, setInfo } from "../../utils/auth";

export default class MyInfoForm extends Component {
  state = {
    areaIdArr: [],
    allAreas: [],
    column1: [],
    column2: [],
    areaName: "",
    creditCode: "",
    title: "",
    regCapital: "",
    contacts: "",
    address: "",
    phone: "",
    location: "",
    x: "",
    y: "",
    estiblishTime: "",
  };
  componentDidMount(): void {
    this.initData();
  }
  componentDidUpdate(): void {}
  initData = () => {
    Req.get("/config/area/list").then((r) => {
      console.log(r);
      if (r.code === 200) {
        let _column1 = r.rows.filter((item) => item.parentId === "0");
        this.setState({
          allAreas: r.rows,
          column1: _column1,
        });
      }
    });

    const user_info = getInfo();
    Req.get(`/company/${user_info?.company.id}`)
      .then((r) => {
        if (r.code === 200) {
          this.setState({
            creditCode: r.data.creditCode,
            location: r.data.location,
            phone: r.data.phone,
            address: r.data.address,
            regCapital: r.data.regCapital,
            estiblishTime: r.data.estiblishTime,
            contacts: r.data.contacts,
            areaName: r.data.areaName,
            title: r.data.title,
            areaId: r.data.areaId,
          });
        }
      })
      .catch((e) => {});
  };
  onOpenLocation = () => {
    Taro.chooseLocation({
      success: (res) => {
        console.log("位置名称：", res.name);
        console.log("经纬度：", res.latitude, res.longitude);
        this.setState({
          location: res.name,
          x: res.longitude,
          y: res.latitude,
        });
      },
      fail: (err) => {
        console.error("错误信息：", err.errMsg);
      },
      complete: () => {
        console.log("选择操作完成");
      },
    });
  };
  render(): ReactNode {
    const {
      areaIdArr,
      column1,
      column2,
      allAreas,
      areaName,
      creditCode,
      title,
      regCapital,
      contacts,
      address,
      phone,
      location,
      x,
      y,
      estiblishTime,
    }: any = this.state;
    return (
      <View className="mif-container">
        <AtNavBar
          leftIconType="chevron-left"
          leftText="返回"
          color="#3051BE"
          onClickLeftIcon={() => {
            Taro.navigateBack();
          }}
        >
          <View>{"编辑我的"}</View>
        </AtNavBar>
        <AtList className="mif-form">
          <Picker
            value={areaIdArr}
            onChange={(e) => {
              const [c1, c2] = e.detail.value;
              this.setState({
                areaName: [column1[c1].name, column2[c2]?.name]
                  .filter((e) => Boolean(e) && e !== "本区域")
                  .join("/"),
              });
            }}
            onColumnChange={(e) => {
              const { column, value: _index } = e.detail;
              if (column === 0) {
                //滑动的是第一列
                let _selectColumn: any = column1[_index];
                let _column2 = allAreas.filter(
                  (item: any) => item.parentId == _selectColumn.id
                );
                console.log(_column2);
                if (_column2.length > 0) {
                  _column2.unshift({
                    id: null,
                    name: "本区域",
                  });
                }
                this.setState({
                  column2: _column2,
                  areaIdArr: [_index],
                });
              } else if (column === 1) {
                const [c1] = areaIdArr;
                this.setState({
                  areaIdArr: [c1, _index],
                });
              }
            }}
            rangeKey="name"
            mode="multiSelector"
            range={[[...column1], [...column2]]}
          >
            <AtListItem
              className="form-list-item form-label-required"
              title="区域"
              arrow="down"
              note={
                <View>
                  <Text>{isEmpty(areaName) ? "请选择" : areaName}</Text>
                </View>
              }
            />
          </Picker>
          <AtListItem
            className="form-list-item no-arrow-space form-label-required"
            title="统一社会信用代码"
            note={
              <View className="code-search">
                <Input
                  value={creditCode}
                  onInput={(e) => {
                    this.setState({
                      creditCode: e.detail.value,
                    });
                  }}
                  placeholder="请输入"
                />
                <AtButton
                  onClick={() => {
                    Req.get("/company/tyc", {
                      creditCode,
                    })
                      .then((r) => {
                        this.setState({
                          title: r.title,
                          contacts: r.contacts,
                          regCapital: r.regCapital,
                          estiblishTime: r.estiblishTime,
                        });
                      })
                      .catch((e) => {});
                  }}
                >
                  查询
                </AtButton>
              </View>
            }
          />
          <AtListItem
            className="form-list-item"
            note={
              <View>
                <Text>{title}</Text>
              </View>
            }
            title="公司（全称）"
          />
          <AtListItem
            className="form-list-item"
            title="法人"
            note={
              <View>
                <Text>{contacts}</Text>
              </View>
            }
          />
          <AtListItem
            className="form-list-item"
            title="注册资本"
            note={
              <View>
                <Text>{regCapital}</Text>
              </View>
            }
          />
          <AtListItem
            className="form-list-item no-active-effect-item"
            title="公司地址"
            note={
              <View>
                <Input
                  value={address}
                  onInput={(e) => {
                    this.setState({
                      address: e.detail.value,
                    });
                  }}
                  placeholder="请输入"
                />
              </View>
            }
          />

          <AtListItem
            className="form-list-item no-active-effect-item"
            title="联系电话"
            note={
              <View>
                <Input
                  disabled
                  value={phone}
                  onInput={(e) => {
                    this.setState({
                      phone: e.detail.value,
                    });
                  }}
                  placeholder="请输入"
                />
              </View>
            }
          />
          <AtListItem
            title="定位"
            onClick={this.onOpenLocation}
            className="form-list-item"
            arrow="down"
            note={
              <View>
                <Text>{isEmpty(location) ? "请选择" : location}</Text>
              </View>
            }
          />
        </AtList>
        <View
          className="p15"
          style={{
            paddingTop: "20px",
          }}
          onClick={() => {
            let _areaId = "";
            if (areaIdArr && areaIdArr.length) {
              let _index = areaIdArr.slice(-1)[0];
              if (areaIdArr.length > 1) {
                _areaId = column2[_index].id;
              } else {
                _areaId = column1[_index].id;
              }
            }
            console.log("areaId",_areaId);

            if (isEmpty(areaName)) {
              Taro.showToast({
                title: "区域不能为空！",
                icon: "none",
                duration: 2000,
              });
              return false;
            }
            if(isEmpty(creditCode)){
              Taro.showToast({
                title: "信用代码不能为空！",
                icon: "none",
                duration: 2000,
              });
              return false;
            }
            Req.post("/company/edit", {
              id: getInfo().company?.id,
              x,
              y,
              location,
              contacts,
              phone,
              regCapital,
              estiblishTime,
              title,
              creditCode,
              address,
              areaId: _areaId,
            })
              .then((r) => {
                if (r.code === 200) {
                  Req.get("/getInfo").then((r) => {
                    setInfo({
                      ...r.user,
                      company: r.company,
                    });
                  });
                  Taro.eventCenter.trigger("refreshData", { force: true });
                  Taro.navigateBack();
                }
              })
              .catch((e) => {});
          }}
        >
          <AtButton
            className="primary-btn-color bottom-btn"
            circle
            type="primary"
          >
            提交
          </AtButton>
        </View>
      </View>
    );
  }
}
